const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const { spawn } = require('child_process');

// 创建窗口函数
function createWindow() {

  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    icon: path.join(__dirname, 'icon.png'),
    autoHideMenuBar: true, 
    titleBarStyle: 'default',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });
  mainWindow.setMenu(null)
  const isDev = !app.isPackaged || process.env.NODE_ENV === 'development';
  if (isDev) {
    mainWindow.loadURL('http://localhost:5173').then(() => {
      mainWindow.webContents.openDevTools();
    })
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
  }

};

// 执行外部程序函数
function executeExternalProgram(exePath, args = []) {
  return new Promise((resolve) => {

    const normalizedExePath = exePath.replace(/^public[\\/]/, '');

    const fullPath = app.isPackaged
      ? path.join(process.resourcesPath, normalizedExePath)
      : path.join(app.getAppPath(), exePath);

    const childProcess = spawn(fullPath, args);

    let output = '';
    let errorOutput = '';

    childProcess.stdout.on('data', (data) => {
      output += data.toString();
    });

    childProcess.stderr.on('data', (data) => {
      errorOutput += data.toString();
    });

    childProcess.on('close', (code) => {
      resolve({
        success: code === 0,
        exitCode: code,
        output: output.trim(),
        error: errorOutput.trim(),
        executedPath: fullPath
      });
    });

    childProcess.on('error', (err) => {
      resolve({
        success: false,
        error: err.message,
        executedPath: fullPath
      });
    });
  });
}

// 处理IPC调用
ipcMain.handle('execute-program', async (event, { exePath, args }) => {
  return await executeExternalProgram(exePath, args);
});

// 应用生命周期
app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});